package com.urerp.web.config;

import javax.sql.DataSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@MapperScan("com.urerp.web.persistence")
@EnableTransactionManagement
public class DataConfig {
	
	private final static Logger logger = LogManager.getLogger(DataConfig.class);
	
	public DataConfig() {
		logger.info("Initialized - DataConfig");
	}
	
	@Value("${db.driver}")
    private String jdbcDriverClassName;
 
    @Value("${db.url}")
    private String jdbcUrl;
 
    @Value("${db.username}")
    private String jdbcUsername;
 
    @Value("${db.password}")
    private String jdbcPassword;

	
	@Bean
    public static PropertyPlaceholderConfigurer dbProperties() {
    	
        final PropertyPlaceholderConfigurer dbProperties = new PropertyPlaceholderConfigurer();
        dbProperties.setLocation(new ClassPathResource("/properties/db.properties"));
        dbProperties.setIgnoreResourceNotFound(true);
        
        return dbProperties;
    }
	
    @Bean
    public DataSource dataSource() {
    	DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName	(jdbcDriverClassName);
        dataSource.setUrl				(jdbcUrl);
        dataSource.setUsername			(jdbcUsername);
        dataSource.setPassword			(jdbcPassword);
     
        return dataSource;
    }
     
    @Bean
    public PlatformTransactionManager txManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return sessionFactory;
    }
}

